<?php
namespace app\serverorder\logic;

use \app\manage\logic\BaseLogic;

/**
 * @author:      李颖
 * @DateTime:    2017-10-13 11:43:43
 * @Description: 订单
 */
class Order extends BaseLogic
{
	protected $name = 'order';
    protected $config = 'db_config_order';
    protected $orderModel = 'app\serverorder\model\Order';


    /*一键购买*/
    public function oneClickBuy($data): array 
    {
    	$saveData['user_id'] = $data['user_id'];
    	$saveData['goods_ids'] = $data['goods_info']['id'];
    	$saveData['goods_numbers'] = $data['number'];
    	$saveData['order_code'] = $data['order_code'];
    	$saveData['status'] = 0;
    	$saveData['exceptions_status'] = 0;
    	$goodsInfo = $this->_regroupGoodsInfo($data);   //给商品信息添加两个字段 choose、 order_info
        //判断传入的价格是否正确
        if($data['final_price'] != $goodsInfo['final_price']){
            return verify_err(null, '商品最终人民币单价传入错误');
        }
        /*if($data['final_currency_price'] != $goodsInfo['final_currency_price']){
            return verify_err(null, '商品最终亚数币单价传入错误');
        }*/
        $saveData['search_fields'] = $goodsInfo['title'] . $goodsInfo['product_code'] . $saveData['order_code'];
    	$saveData['goods_infos'][] = $goodsInfo;
        $saveData['max_integral_deduction'] = $goodsInfo['goods_attrs']['integral_deduction']['value'] ?? 0;
    	$saveData['total_price'] = bcmul($goodsInfo['final_price'], $goodsInfo['order_number']);
    	$saveData['total_other_price'] = ['currency'=>bcmul($goodsInfo['final_currency_price'], $goodsInfo['order_number'], 4)];
        $orderModel = $this->model($this->orderModel);
    	$res = $orderModel->save($saveData);
        if(!$res){
            return auto_failure(null, '订单提交失败');
        }
        $returnRes['max_integral_deduction'] = $goodsInfo['goods_attrs']['integral_deduction']['value'] ?? 0;
        $returnRes['order_code'] = $saveData['order_code'];
        $returnRes['total_price'] = $saveData['total_price'];
        $returnRes['total_other_price'] = $saveData['total_other_price'];
        $returnRes['order_id'] = $orderModel->id;
        return auto_return($returnRes, '订单提交成功');
    }

    /*一键购买 - 重新组建商品信息 追加 choose、order_info 字段*/
    //不可注释掉goods_attrs
    protected function _regroupGoodsInfo(array $data): array 
    {
    	$choose = [];
    	$final_price = $data['goods_info']['price'];
    	$final_currency_price = $data['goods_info']['orther_price']['currency'];
    	foreach ($data['goods_attrs'] as $k => $v) {
    		$choose[$v['en_name']] = $v;
    		isset($v['change_price']) && $final_price = bcadd($final_price, $v['change_price']);
    		isset($v['change_currency_price']) && $final_currency_price = bcadd($final_currency_price, $v['change_currency_price'], 4);
    	}
    	$data['goods_info']['choose'] = $choose;
        $data['goods_info']['order_number'] = $data['number'];
        $data['goods_info']['final_price'] = $final_price;
        $data['goods_info']['final_currency_price'] = $final_currency_price;
        $data['goods_info']['final_total_price'] = bcmul($final_price, $data['number']);
        $data['goods_info']['final_total_currency_price'] = bcmul($final_currency_price, $data['number'], 4);
    	return $data['goods_info'];
    }


    /*购物车中结算*/
    public function settlement($data): array 
    {
        $saveData['user_id'] = $data['user_id'];
        $saveData['goods_ids'] = implode(",", array_column($data['cartList'], 'goods_id'));
        $saveData['order_code'] = $data['order_code'];
        $data = $this->_regroupOrderGoodsInfo($data);
        $saveData['search_fields'] = $data['search_fields'];
        $saveData['goods_infos'] = $data['goods_infos'];
        $saveData['max_integral_deduction'] = $data['max_integral_deduction'];
        $saveData['total_price'] = $data['total_price'];
        $saveData['total_other_price'] = $data['total_other_price'];
        $saveData['goods_numbers'] = $data['goods_numbers'];
        $saveData['status'] = 0;
        $saveData['exceptions_status'] = 0;
        $orderModel = $this->model($this->orderModel);
        $res = $orderModel->save($saveData);
        if(!$res){
            return auto_failure(null, '订单提交失败');
        }
        $returnRes['max_integral_deduction'] = $data['max_integral_deduction'];
        $returnRes['order_code'] = $saveData['order_code'];
        $returnRes['total_price'] = $saveData['total_price'];
        $returnRes['total_other_price'] = $saveData['total_other_price'];
        $returnRes['order_id'] = $orderModel->id;
        return auto_return($returnRes, '订单提交成功');
    }

    /*重组订单信息中的商品信息*/
    //不可注释掉goods_attrs
    protected function _regroupOrderGoodsInfo($data): array 
    {
        $max_integral_deduction = 0; //最大积分抵扣值
        $goodsInfo = [];
        $total_price = 0;
        $total_currency_price = 0;
        $goods_numbers = 0;
        $search_fields = $data['order_code'];
        foreach ($data['cartList'] as $k => $v) {
            $oneGoods = $v['goods_info'];
            $oneGoods['order_number'] = $v['number'];
            $oneGoods['final_price'] = $v['price'];
            $oneGoods['final_currency_price'] = $v['orther_price']['currency'];
            $oneGoods['final_total_price'] = bcmul($v['price'], $v['number']);
            $oneGoods['final_total_currency_price'] = bcmul($v['orther_price']['currency'], $v['number'], 4);
            isset($v['goods_info']['goods_attrs']['integral_deduction']['value']) && $max_integral_deduction = bcadd($max_integral_deduction, $v['goods_info']['goods_attrs']['integral_deduction']['value']);
            $total_price = bcadd($total_price, $oneGoods['final_total_price']);
            $total_currency_price = bcadd($total_currency_price, $oneGoods['final_total_currency_price'], 4);
            $goods_numbers = bcadd($goods_numbers, $v['number']);
            $oneSearch = $v['goods_info']['title'] . $v['goods_info']['product_code'];
            $search_fields .= $oneSearch;
            $goodsInfo[] = $oneGoods;
        }
        $data['max_integral_deduction'] = $max_integral_deduction;
        $data['goods_infos'] = $goodsInfo;
        $data['total_price'] = $total_price;
        $data['total_other_price'] = ['currency'=>$total_currency_price];
        $data['goods_numbers'] = $goods_numbers;
        $data['search_fields'] = $search_fields;
        return $data;
    }

    /*获取我的订单信息*/
    public function orderInfo($data): array 
    {
        $_where['user_id'] = $data['user_id'];
        $_where['id'] = $data['id'];
        $_where['is_del'] = 0;
        $res = $this->model($this->orderModel)->where($_where)->find();
        return auto_return($res, '成功找到该订单', '该订单获取失败');
    }

    /*获取我的订单列表*/
    public function myOrderList($data): array 
    {
        $data['is_del'] = 0;
        return $this->_orderList($data); 
    }

    /*获取订单列表 分页数据*/
    public function _orderList($data): array 
    {
        $_where['is_del'] = $data['is_del'] ?? ['neq', 2];
        isset($data['user_id']) && $_where['user_id'] = $data['user_id'];
        if(isset($data['status']) && $data['status'] !== ''){
            $_where['status'] = $data['status'];
            $_where['exceptions_status'] = 0;
        }
        if(isset($data['time'])){
            $threeMonthTime = mktime(0, 0, 0, date("m")-3, date("d"), date("Y"));
            if($data['time'] == 'threeMonthAgo'){   
                $_where['create_time'] = ['lt',$threeMonthTime];    //3个月以前
            }elseif($data['time'] == 'threeMonth'){   
                $_where['create_time'] = ['gt',$threeMonthTime];    //3个月之内
            }
        }
        if(isset($data['keyword']) && $data['keyword']){
            $_where['search_fields'] = ['like', '%' . $data['keyword'] . '%'];
        }
        $res = $this->model($this->orderModel)
                    ->where($_where)
                    ->order('id DESC')
                    ->paginate(null, false, ['page'=>$data['page'], 'list_rows'=>$data['listRows']])
                    ->toArray();
        return auto_return_page($res);
    }

    /*取消我的订单 未付款的正常订单*/
    public function cancelMyOrder($data): array 
    {
        $_where['status'] = 0;
        $_where['exceptions_status'] = 0;
        $_where['user_id'] = $data['user_id'];
        $_where['id'] = $data['id'];
        $_where['is_del'] = 0;
        $saveData['exceptions_status'] = 1;
        $res = $this->model($this->orderModel)->save($saveData, $_where);
        return auto_return($res, '成功取消订单', '取消订单失败');
    }

    /*删除我的订单 取消的订单 超时的订单*/
    public function delMyOrder($data): array 
    {
        $_where['user_id'] = $data['user_id'];
        $_where['id'] = $data['id'];
        $_where['is_del'] = 0;
        // 暂时先加一个零,正常加0需要是status === 1 TODO 李全春
        $_where['exceptions_status'] = ['in', [0,1,2]];
        $saveData['is_del'] = 1;

        $res = $this->model($this->orderModel)->save($saveData, $_where);
        return auto_return($res, '成功删除订单', '删除订单失败');
    }

    /*我的订单 - 去支付*/
    public function payOrder($data): array 
    {
        $_where['id'] = $data['id'];
        $_where['user_id'] = $data['user_id'];
        $_where['status'] = 0;
        $_where['exceptions_status'] = 0;
        $_where['is_del'] = 0;
        $orderInfo = $this->model($this->orderModel)->where($_where)->find();
        if(!$orderInfo){
            return verify_err(null, '未找到符合条件的订单');
        }
        $saveData['status'] = 1;
        $saveData['integral_deduction'] = $data['integral_deduction'];
        $saveData['integral_deduction_money'] = $data['integral_deduction_money'];
        $saveData['integral_deduction_currency'] = $data['integral_deduction_currency'];
        $saveData['pay_method'] = $data['pay_method'];
        $saveData['pay_time'] = NOW;
        $data['integral_deduction_money'] && $saveData['total_price'] = bcsub($orderInfo['total_price'], $data['integral_deduction_money']);
        $data['integral_deduction_currency'] && $saveData['total_other_price'] = ['currency'=>bcsub($orderInfo['total_other_price']['currency'], $data['integral_deduction_currency'])];
        $res = $this->model($this->orderModel)->save($saveData, $_where);
        return auto_return($res, '成功支付订单', '支付订单失败');
    }

    /*后台获取所有订单分页列表*/
    public function allOrderList($data): array 
    {
        $_where['is_del'] = ['neq', 2];
        $data['keywords'] && $_where['search_fields'] = ['like', '%' . $data['keywords'] . '%'];
        $list = $this->model($this->orderModel)
                    ->order('id desc')
                    ->where($_where)
                    ->paginate(null, false, ['page'=>$data['page'], 'list_rows'=>$data['listRows']])
                    ->toArray();
        return auto_return_page($list);
    }

    /*后台获取某订单信息*/
    public function adminOrderInfo($data): array 
    {
        $_where['id'] = $data['id'];
        $_where['is_del'] = ['neq', 2];
        $info = $this->model($this->orderModel)->where($_where)->find();
        return auto_return($info);
    }

    /*获取我的待付款数额*/
    public function myObligation($data): array 
    {
        $_where['user_id'] = $data['user_id'];
        $_where['status'] = 0;
        $_where['exceptions_status'] = 0;
        $_where['is_del'] = 0;
        $count = $this->model($this->orderModel)->where($_where)->count();
        return auto_return($count, '成功获取我的待付款数额');
    }

    /*未付款的订单自动关闭*/
    public function orderAutoClose($data): array 
    {
        $time = bcsub(NOW, bcmul(3600, $data['order_auto_close']));
        $_where['status'] = 0;
        $_where['exceptions_status'] = 0;
        $_where['is_del'] = 0;
        $_where['create_time'] = ['gt', $time];
        $res = $this->model($this->orderModel)->save(['exceptions_status'=>2], $_where);
        return auto_return($res);
    }
    /*获取最近一周的用户增量和用户总数*/
    public function orderIncreTendency($data): array 
    {
        $dbDateFormat = $data['dbDateFormat'];
        $Db = \think\Db::connect(config('db_config_order'));
        $weekSql = "select count(*) as counts, FROM_UNIXTIME(create_time, '$dbDateFormat') as create_time_date from tp_order where create_time > UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 1 WEEK)) group by create_time_date";
        $queryRes = $Db->query($weekSql);
        $weeks = week_key_array($data['dateFormat']);
        $delQueryRes = [];
        foreach ($queryRes as $k => $v) {
            $delQueryRes[$v['create_time_date']] = $v['counts'];
        }
        $weekIncre = array_merge($weeks, $delQueryRes);
        $newWeekIncre = [];
        foreach ($weekIncre as $k => $v) {
            $one['date'] = $k;
            $one['value'] = $v;
            $newWeekIncre[] = $one;
        }
        $res['weekIncre'] = $newWeekIncre;
        $res['total'] = $this->db()->count();
        return auto_return($res);
    }

}